import pandas as pd
import requests
from bs4 import BeautifulSoup
from pip._internal.utils import logging
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time
from selenium.webdriver.common.action_chains import ActionChains

# 配置ChromeOptions，设置detach为True，使浏览器窗口不会自动关闭
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("detach", True)

# 指定chromedriver的实际路径
chromedriver_path = r'C:\Program Files\Google\Chrome\Application\chromedriver.exe'
service = Service(executable_path=chromedriver_path)

# 创建Chrome浏览器实例
driver = webdriver.Chrome(options=chrome_options, service=service)


# 打开懂车帝
driver.get("https://www.dongchedi.com/sales")

# 找到页面的body元素
body_element = driver.find_element(By.TAG_NAME, "body")

#向下滚动界面
def down():
    for i in range(0, 300):
        body_element.send_keys(Keys.DOWN)

def get_html_from_url():
    html = driver.page_source
    return html

# 读取数据
def parse_single_html(html):
    hash_sale = {}
    soup = BeautifulSoup(html, 'html.parser')
    cars = (soup.find("div",class_="jsx-495096444 tw-col-span-5")).find_all("li",class_="list_item__3gOKl")
    datas = []
    for i in range(0,75):
        car = cars[i]
        car_name = car.find("a",class_="tw-font-semibold").get_text()
        car_type = car.find("span",class_="tw-text-12 tw-text-color-gray-700 tw-ml-6").get_text()
        car_sale_price = car.find("p",class_="tw-leading-22 tw-text-color-red-500 tw-font-semibold").get_text()
        car_sale_count = car.find("p",class_="tw-text-18 tw-font-semibold tw-leading-28").get_text()
        car_sale_count = car_sale_count.replace(",","")
        car_com = car_type.split("/")[0]
        if car_com not in hash_sale:
            hash_sale[car_com] = int(car_sale_count)
        else:
            hash_sale[car_com] += int(car_sale_count)
        # print((i+1),"\t"+car_name+"\t"+car_type+"\t"+car_sale_price+"\t"+car_sale_count)
        datas.append({
            "排名":(i+1),
            "车名":car_name,
            "品牌/车型":car_type,
            "价格":car_sale_price,
            "本月销量":car_sale_count
        })
    print(hash_sale)
    return datas


# 点击切换月份
def click(name):
    button = driver.find_element(By.CSS_SELECTOR, ".tw-relative.more_item__2UARp")
    actions = ActionChains(driver)
    actions.move_to_element(button)
    actions.perform()  # 执行构建好的鼠标动作链，实现鼠标悬停效果
    button2 = driver.find_elements(By.CSS_SELECTOR, "a.more_option___6xpL")
    for b in button2:
        element_text = b.text  # 获取元素的文本内容
        if element_text == name:
            b.click()  # 如果文本内容符合要求，点击该按钮


names = ["2024年11月","2024年10月","2024年09月","2024年08月","2024年07月","2024年06月"]
for name in names:
    print(name)
    click(name)
    down()
    html=get_html_from_url()
    datas = parse_single_html(html)
    # df = pd.DataFrame(datas)  # 结果存入 excel
    # df.to_excel(f"懂车帝{name}销量排行榜.xlsx")
driver.quit()


